/* AddressBar.java
 * Author: liuex
 * 2007-12-22 ����02:33:04
 *
 * Note: 
 */
package org.lex.ftp.ui.explorer;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.JTextField;

import org.lex.catalog.CatalogEvent;
import org.lex.catalog.CatalogListener;
import org.lex.ftp.model.FTPModel;
import org.lex.ftp.model.NullFTPModel;
import org.lex.swing.SelectAllWhenGainFocus;


public class AddressBar extends JPanel implements CatalogListener {
	private String directory = null;
	private JTextField addressTextField = null;
	private FTPModel model = NullFTPModel.getInstance();

	public AddressBar() {
		this("");
	}

	public AddressBar(String directory) {
		super();
		this.directory = directory;
		this.initialize();
	}

	public void setFTPModel(FTPModel model) {
		this.model.removeCatalogListener(this);
		this.model = model;
		this.model.addCatalogListener(this);
		this.catalogChanged(new CatalogEvent(model, model.getCatalog()));
	}

	public void catalogChanged(CatalogEvent e) {
		this.setDirectory(String.valueOf(e.getCatalog()));
	}

	public String getDirectory() {
		return this.directory;
	}

	public void setDirectory(String directory) {
		this.directory = directory;
		this.addressTextField.setText(this.directory);
		this.addressTextField.setCaretPosition(directory.length());
	}

	private void initialize() {
		this.setLayout(new BorderLayout());
		this.add(getAddressTextField(), BorderLayout.CENTER);
	}

	public JTextField getAddressTextField() {
		if (addressTextField == null) {
			addressTextField = new JTextField();
			addressTextField.setText(this.directory);
			addressTextField.addFocusListener(SelectAllWhenGainFocus.getInstance());
			addressTextField.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					model.setCatalog(addressTextField.getText().trim());
				}
			});
		}
		return addressTextField;
	}
}
